// stores/circle_posts.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
    createCirclePost,
    getCirclePosts,
    getCirclePostDetail,
    updateCirclePost,
    deleteCirclePost,
    likeCirclePost,
    unlikeCirclePost,
    getUserCirclePosts,
    getHotCirclePosts,
    searchCirclePosts,
    createComment,
    getComments,
    getCommentDetail,
    updateComment,
    deleteComment,
    getCommentReplies
} from '@/api/circle_post'
import { uploadImage } from '@/api/upload'

export const useCirclePostsStore = defineStore('circlePosts', () => {
    // 帖子相关状态
    const posts = ref([])
    const currentPost = ref(null)
    const userPosts = ref([])
    const hotPosts = ref([])
    const searchedPosts = ref([])
    const postsLoading = ref(false)
    const postsHasMore = ref(true)
    const postsPage = ref(1)
    const postsPageSize = ref(10)

    // 评论相关状态
    const comments = ref([])
    const currentComment = ref(null)
    const commentReplies = ref([])
    const commentsLoading = ref(false)
    const commentsHasMore = ref(true)
    const commentsPage = ref(1)
    const commentsPageSize = ref(20)

    // 帖子相关 Actions

    // 创建帖子
    const createPostAction = async (data) => {
        try {
            const response = await createCirclePost(data)
            if (response.code === 0) {
                // 将新帖子添加到列表开头
                posts.value.unshift(response.data)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取圈子帖子列表
    const fetchCirclePostsAction = async (circleId, params = {}) => {
        try {
            postsLoading.value = true
            const response = await getCirclePosts(circleId, {
                page: postsPage.value,
                pageSize: postsPageSize.value,
                ...params
            })

            if (response.code === 0) {
                if (params.page === 1 || postsPage.value === 1) {
                    posts.value = response.data.list || []
                } else {
                    posts.value = [...posts.value, ...(response.data.list || [])]
                }

                // 检查是否还有更多数据
                const currentList = response.data.list || []
                postsHasMore.value = currentList.length === postsPageSize.value

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        } finally {
            postsLoading.value = false
        }
    }

    // 加载更多帖子
    const loadMorePostsAction = async (circleId, params = {}) => {
        if (!postsHasMore.value || postsLoading.value) return

        postsPage.value += 1
        return await fetchCirclePostsAction(circleId, params)
    }

    // 重置帖子分页
    const resetPostsPaginationAction = () => {
        postsPage.value = 1
        postsHasMore.value = true
        posts.value = []
    }

    // 获取帖子详情
    const fetchPostDetailAction = async (postId) => {
        try {
            const response = await getCirclePostDetail(postId)
            if (response.code === 0) {
                currentPost.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新帖子
    const updatePostAction = async (postId, data) => {
        try {
            const response = await updateCirclePost(postId, data)
            if (response.code === 0) {
                // 更新本地帖子数据
                const index = posts.value.findIndex(post => post.post_id === postId)
                if (index !== -1) {
                    posts.value[index] = { ...posts.value[index], ...data }
                }

                if (currentPost.value && currentPost.value.post_id === postId) {
                    currentPost.value = { ...currentPost.value, ...data }
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 删除帖子
    const deletePostAction = async (postId) => {
        try {
            const response = await deleteCirclePost(postId)
            if (response.code === 0) {
                // 从本地列表中移除
                posts.value = posts.value.filter(post => post.post_id !== postId)

                if (currentPost.value && currentPost.value.post_id === postId) {
                    currentPost.value = null
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 点赞帖子
    const likePostAction = async (postId) => {
        try {
            const response = await likeCirclePost(postId)
            if (response.code === 0) {
                // 更新本地帖子点赞数
                updatePostLikeCount(postId, 1)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 取消点赞帖子
    const unlikePostAction = async (postId) => {
        try {
            const response = await unlikeCirclePost(postId)
            if (response.code === 0) {
                // 更新本地帖子点赞数
                updatePostLikeCount(postId, -1)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新帖子点赞数
    const updatePostLikeCount = (postId, change) => {
        // 更新帖子列表中的点赞数
        const postIndex = posts.value.findIndex(post => post.post_id === postId)
        if (postIndex !== -1) {
            const post = posts.value[postIndex]
            post.like_count = Math.max(0, post.like_count + change)
        }

        // 更新当前帖子的点赞数
        if (currentPost.value && currentPost.value.post_id === postId) {
            currentPost.value.like_count = Math.max(0, currentPost.value.like_count + change)
        }
    }

    // 获取用户帖子列表
    const fetchUserPostsAction = async (params = {}) => {
        try {
            const response = await getUserCirclePosts(params)
            if (response.code === 0) {
                userPosts.value = response.data.list || response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取热门帖子
    const fetchHotPostsAction = async (params = {}) => {
        try {
            const response = await getHotCirclePosts(params)
            if (response.code === 0) {
                hotPosts.value = response.data || []
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 搜索帖子
    const searchPostsAction = async (params = {}) => {
        try {
            const response = await searchCirclePosts(params)
            if (response.code === 0) {
                searchedPosts.value = response.data.list || response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 评论相关 Actions

    // 创建评论
    const createCommentAction = async (data) => {
        try {
            const response = await createComment(data)
            if (response.code === 0) {
                // 将新评论添加到列表开头
                comments.value.unshift(response.data)

                // 只有顶级评论才更新帖子的评论计数
                if (!data.parent_id) {
                    updatePostCommentCount(data.circle_post_id, 1)
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取评论列表
    const fetchCommentsAction = async (params = {}) => {
        try {
            commentsLoading.value = true
            const response = await getComments({
                page: commentsPage.value,
                pageSize: commentsPageSize.value,
                ...params
            })

            if (response.code === 0) {
                if (params.page === 1 || commentsPage.value === 1) {
                    comments.value = response.data.list || []
                } else {
                    comments.value = [...comments.value, ...(response.data.list || [])]
                }

                // 检查是否还有更多数据
                const currentList = response.data.list || []
                commentsHasMore.value = currentList.length === commentsPageSize.value

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        } finally {
            commentsLoading.value = false
        }
    }
    // 加载更多评论
    const loadMoreCommentsAction = async (params = {}) => {
        if (!commentsHasMore.value || commentsLoading.value) return

        commentsPage.value += 1
        return await fetchCommentsAction(params)
    }

    // 重置评论分页
    const resetCommentsPaginationAction = () => {
        commentsPage.value = 1
        commentsHasMore.value = true
        comments.value = []
    }

    // 获取评论详情
    const fetchCommentDetailAction = async (commentId) => {
        try {
            const response = await getCommentDetail(commentId)
            if (response.code === 0) {
                currentComment.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新评论
    const updateCommentAction = async (commentId, data) => {
        try {
            const response = await updateComment(commentId, data)
            if (response.code === 0) {
                // 更新本地评论数据
                const index = comments.value.findIndex(comment => comment.comment_id === commentId)
                if (index !== -1) {
                    comments.value[index] = { ...comments.value[index], ...data }
                }

                if (currentComment.value && currentComment.value.comment_id === commentId) {
                    currentComment.value = { ...currentComment.value, ...data }
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 删除评论
    const deleteCommentAction = async (commentId) => {
        try {
            const response = await deleteComment(commentId)
            if (response.code === 0) {
                // 从本地列表中移除
                const deletedComment = comments.value.find(comment => comment.comment_id === commentId)
                comments.value = comments.value.filter(comment => comment.comment_id !== commentId)

                // 更新帖子的评论计数
                if (deletedComment) {
                    updatePostCommentCount(deletedComment.circle_post_id, -1)
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取评论回复列表
    const fetchCommentRepliesAction = async (params = {}) => {
        try {
            const response = await getCommentReplies(params)
            if (response.code === 0) {
                commentReplies.value = response.data.list || response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新帖子评论计数
    const updatePostCommentCount = (postId, change) => {
        // 更新帖子列表中的评论计数
        const postIndex = posts.value.findIndex(post => post.post_id === postId)
        if (postIndex !== -1) {
            const post = posts.value[postIndex]
            post.comment_count = Math.max(0, post.comment_count + change)
        }

        // 更新当前帖子的评论计数
        if (currentPost.value && currentPost.value.post_id === postId) {
            currentPost.value.comment_count = Math.max(0, currentPost.value.comment_count + change)
        }
    }

    // 添加图片上传方法
    const uploadCirclePostImage = async (file) => {
        try {
            const formData = new FormData()
            formData.append('file', file)

            const response = await uploadImage(formData)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 添加多图片上传方法
    const uploadCirclePostImages = async (files) => {
        try {
            const uploadPromises = files.map(file => uploadCirclePostImage(file))
            const results = await Promise.all(uploadPromises)

            // 返回所有上传成功的图片URL
            const imageUrls = results.map(result => result.data.url)
            return Promise.resolve({
                code: 0,
                data: {
                    urls: imageUrls
                },
                msg: '上传成功'
            })
        } catch (error) {
            return Promise.reject(error)
        }
    }

    return {
        // 帖子相关状态
        posts,
        currentPost,
        userPosts,
        hotPosts,
        searchedPosts,
        postsLoading,
        postsHasMore,
        postsPage,
        postsPageSize,

        // 评论相关状态
        comments,
        currentComment,
        commentReplies,
        commentsLoading,
        commentsHasMore,
        commentsPage,
        commentsPageSize,

        // 帖子相关 Actions
        createPostAction,
        fetchCirclePostsAction,
        loadMorePostsAction,
        resetPostsPaginationAction,
        fetchPostDetailAction,
        updatePostAction,
        deletePostAction,
        likePostAction,
        unlikePostAction,
        fetchUserPostsAction,
        fetchHotPostsAction,
        searchPostsAction,
        uploadCirclePostImage,
        uploadCirclePostImages,

        // 评论相关 Actions
        createCommentAction,
        fetchCommentsAction,
        loadMoreCommentsAction,
        resetCommentsPaginationAction,
        fetchCommentDetailAction,
        updateCommentAction,
        deleteCommentAction,
        fetchCommentRepliesAction
    }
})